package fr.neyb.wesb.core.data.io.impl.sb;

import java.io.IOException;
import java.io.Reader;

import fr.neyb.wesb.core.data.content.Record;
import fr.neyb.wesb.core.data.io.IOTextFormat;
import fr.neyb.wesb.core.data.io.RecordReader;
import fr.neyb.wesb.core.data.io.impl.AbstractRecordIO;

public class SBRecordReader extends AbstractRecordIO implements RecordReader {

	private final static class CharSequenceReader extends Reader {
		private final CharSequence content;
		private int pos = 0;

		public CharSequenceReader(CharSequence content) {
			this.content = content;
		}

		@Override
		public int read(char[] cbuf, int off, int len) throws IOException {
			int currRelPos;
			for (currRelPos = 0; currRelPos < len; currRelPos++) {
				if (pos + currRelPos < content.length()) {
					cbuf[off + currRelPos] = content.charAt(pos + currRelPos);
				} else {
					pos+=currRelPos;
					return -1;
				}
			}
			pos+=currRelPos;
			return currRelPos;
		}

		@Override
		public void close() throws IOException {
		}
	}

	private boolean open = false;
	private final CharSequenceReader csr;
	private final IOTextFormat textFormat;

	public SBRecordReader(CharSequence content, IOTextFormat textFormat) {
		super(textFormat.getDescriptor());
		csr=new CharSequenceReader(content);
		this.textFormat=textFormat;
	}

	@Override
	public boolean open() {
		boolean result = !open;
		open = true;
		return result;
	}

	@Override
	public boolean close() {
		boolean result = open;
		open = false;
		return result;
	}

	@Override
	public Record read() {
		try {
			return textFormat.read(csr);
		} catch (IOException e) {
			throw new AssertionError();
		}
	}
}
